<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="物品名称" prop="psGoodsId">
        <el-input
          v-model="queryParams.params.psGoodsName"
          placeholder="请输入物品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="日期查询" prop="psGoodsId">
        <el-date-picker
          @change="timeQuery"
          v-model="value1"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd HH:mm:ss"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="出库单位" prop="psUnitId">
        <el-select
          v-model="queryParams.params.psUnitId"
          placeholder="请输入出库单位"
          clearable
          multiple
          style="width: 100%"
        >
          <el-option
            v-for="dict in unitList"
            :key="dict.id"
            :label="dict.puName"
            :value="dict.id"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="类别" prop="psUnitId">
        <el-select
          v-model="queryParams.params.goodsTypeId"
          placeholder="请输入出库单位"
          clearable
          multiple
          style="width: 100%"
        >
          <el-option
            v-for="dict in dict.type.ps_goods_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['procurement-system:outbound:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['procurement-system:outbound:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['procurement-system:outbound:remove']"
          >删除回退</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport('procurement-system/outbound/export')"
          v-hasPermi="['procurement-system:outbound:export']"
          >配送清单导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport('procurement-system/outbound/export2')"
          v-hasPermi="['procurement-system:outbound:export']"
          >总表导出</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport('procurement-system/outbound/export3')"
          v-hasPermi="['procurement-system:outbound:export']"
          >月总表导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="outboundList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="出库单位" align="center" prop="psUnitId">
        <template #default="scope">
          <div>
            {{
              unitList.find((item) => item.id === scope.row.psUnitId)
                ? unitList.find((item) => item.id === scope.row.psUnitId).puName
                : scope.row.psUnitId
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="数量单位" align="center" prop="poUnit">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.ps_goods_unit"
            :value="scope.row.poUnit"
          />
        </template>
      </el-table-column>
      <el-table-column label="物品名称" align="center" prop="psGoodsId">
        <template #default="scope">
          <div>
            {{
              goodsList.find((item) => item.goodsId === scope.row.psGoodsId)
                ? goodsList.find((item) => item.goodsId === scope.row.psGoodsId)
                    .goodsName
                : scope.row.psGoodsId
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="出库数量" align="center" prop="poNum" />
      <el-table-column
        label="库存剩余"
        align="center"
        prop="poPriceRemaining"
      />
      <el-table-column label="单价" align="center" prop="poPrice" />
      <el-table-column label="出库金额" align="center" prop="poAmount" />

      <el-table-column label="物品类别" align="center" prop="goodsType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.ps_goods_type"
            :value="scope.row.goodsType"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="送货时间"
        align="center"
        prop="poDeliveryDate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.poDeliveryDate, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="出库时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建人" align="center" prop="createByName" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['procurement-system:outbound:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['procurement-system:outbound:remove']"
            >删除回退</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      :page-sizes="[10, 50, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000]"
    />

    <!-- 添加或修改物品出库对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="出库单位" prop="psUnitId">
          <el-select
          :disabled="!isAdd"
          filterable
            v-model="form.psUnitId"
            placeholder="请输入出库单位"
            style="width: 100%"
          >
            <el-option
              v-for="dict in unitList"
              :key="dict.id"
              :label="dict.puName"
              :value="dict.id"
            ></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="物品名称" prop="psGoodsId">
          <el-select
          filterable
          
          :disabled="!isAdd"
            @change="checkGoodsId"
            v-model="form.psGoodsId"
            placeholder="请选择物品名称"
            style="width: 100%"
          >
            <el-option
              v-for="dict in goodsList"
              :key="dict.goodsId"
              :label="dict.goodsName"
              :value="dict.goodsId"
            ></el-option>
          </el-select>
          <div v-if="form.psGoodsId" style="color: #e6a23c">
            当前物品库存数量：{{
              goodsList.find((item) => item.goodsId === form.psGoodsId).goodsNum
            }}
          </div>
        </el-form-item>


        <el-form-item label="数量单位" prop="poUnit">
          <el-select
          filterable
          
          :disabled="!isAdd"
            v-model="form.poUnit"
            placeholder="请选择数量单位"
            style="width: 100%"
          >
            <el-option
              v-for="dict in dict.type.ps_goods_unit"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          :label-width="goodsNum < 0 ? '' : '100px'"
          :label="goodsNum < 0 ? '出库数量' : '出库数量(' + goodsNum + ')'"
          prop="poNum"
        >
          <el-input-number
            :min="0"
            
          :disabled="!isAdd"
            v-model="form.poNum"
            placeholder="请输入出库数量"
            :controls="false"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="送货日期" prop="poDeliveryDate">
          <el-date-picker
            v-model="form.poDeliveryDate"
            type="date"
            placeholder="送货日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="单价" prop="poPrice">
          <el-input-number
            :min="0"
            :precision="2"
            v-model="form.poPrice"
            placeholder="请输入单价"
            :controls="false"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listOutbound,
  getOutbound,
  delOutbound,
  addOutbound,
  updateOutbound,
} from "@/api/procurement-system/outbound";
import { listUnit } from "@/api/procurement-system/unit";
import { listGoods } from "@/api/procurement-system/goods";

export default {
  name: "Outbound",
  dicts: ["ps_goods_unit", "ps_goods_type"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物品出库表格数据
      outboundList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        psUnitId: null,
        poNum: null,
        poUnit: null,
        poPrice: null,
        psGoodsId: null,
        params: {},
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        psUnitId: {
          required: true,
          message: "请输入出库单位",
          trigger: "blur",
        },
        psGoodsId: {
          required: true,
          message: "请选择物品名称",
          trigger: "blur",
        },
        poUnit: { required: true, message: "请选择数量单位", trigger: "blur" },
        poNum: { required: true, message: "请输入出库数量", trigger: "blur" },
        poDeliveryDate: { required: true, message: "请输入送货日期", trigger: "blur" }
      },
      unitList: [],
      goodsList: [],
      //商品库存
      goodsNum: 0,
      value1: {},
      isAdd: false
    };
  },
  created() {
    this.getList();
    this.getListUnit();
    this.getListGoods();
  },
  methods: {
    timeQuery(varr) {
      if (varr && varr.length > 0) {
        const createTimeStartDate = new Date(varr[0]);
        console.log(this.$dayjs(createTimeStartDate).format('YYYY-MM-DD HH:mm:ss'))

        this.queryParams.params.createTimeStart = this.$dayjs(createTimeStartDate).format('YYYY-MM-DD HH:mm:ss');
        const createTimeEndDate = new Date(varr[1]);
        this.queryParams.params.createTimeEnd = this.$dayjs(createTimeEndDate).format('YYYY-MM-DD HH:mm:ss');;
      } else {
        this.queryParams.params.createTimeStart = null;
        this.queryParams.params.createTimeEnd = null;
      }
    },
    checkGoodsId(id) {
      var da = this.goodsList.find((da) => da.goodsId === id);
      if (da) {
        this.goodsNum = da.goodsNum;
        this.form.poUnit = da.goodsUnit;
        this.form.goodsType = da.goodsType;
      }
    },
    getListUnit() {
      listUnit({ pageNum: 1, pageSize: 9999 }).then((response) => {
        this.unitList = response.rows;
      });
    },
    getListGoods() {
      listGoods({ pageNum: 1, pageSize: 9999 }).then((response) => {
        this.goodsList = response.rows;
      });
    },
    /** 查询物品出库列表 */
    getList() {
      this.loading = true;
      if (
        this.queryParams.params.psUnitId &&
        this.queryParams.params.psUnitId.length === 0
      ) {
        delete this.queryParams.params.psUnitId;
      }

      if (
        this.queryParams.params.goodsTypeId &&
        this.queryParams.params.goodsTypeId.length === 0
      ) {
        delete this.queryParams.params.goodsTypeId;
      }

      listOutbound(this.queryParams).then((response) => {
        this.outboundList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        psUnitId: null,
        poNum: null,
        poUnit: null,
        poPrice: null,
        psGoodsId: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        poPriceRemaining: null,
        poDeliveryDate: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      //修改 送货时间 出库单位
      let psUnitId = localStorage.getItem('出库单位')
      let poDeliveryDate = localStorage.getItem('送货时间')
      if(psUnitId){
        this.form.psUnitId = psUnitId
      }
      if(poDeliveryDate){
        this.form.poDeliveryDate = poDeliveryDate
      }
      this.open = true;
      this.isAdd = true
      this.title = "添加物品出库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      
      this.isAdd = false
      this.goodsNum = -1;
      this.reset();
      const id = row.id || this.ids;
      getOutbound(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物品出库";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateOutbound(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addOutbound(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();

              //保存 送货时间 出库单位
              localStorage.setItem('出库单位',this.form.psUnitId)
              localStorage.setItem('送货时间',this.form.poDeliveryDate)
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除物品出库编号为"' + ids + '"的数据项？')
        .then(function () {
          return delOutbound(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport(url) {
      if (
        this.queryParams.params.psUnitId &&
        this.queryParams.params.psUnitId.length === 0
      ) {
        delete this.queryParams.params.psUnitId;
      }
      if (this.ids && this.ids.length > 0) {
        this.queryParams.params.ids = this.ids;
      } else {
        delete this.queryParams.params.ids;
      }
      this.download(
        url,
        {
          ...this.queryParams,
        },
        `outbound_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
